package com.gitee.simons.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.simons.common.bean.JsonResult;
import com.gitee.simons.common.exception.ServiceException;
import com.gitee.simons.system.entity.dto.UserLoginParamDto;
import com.gitee.simons.system.entity.po.OauthClientDetails;
import com.gitee.simons.system.entity.po.SysRole;
import com.gitee.simons.system.entity.po.SysUser;
import com.gitee.simons.system.service.OauthClientDetailsService;
import com.gitee.simons.system.service.SysRoleService;
import com.gitee.simons.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;

/**
 * @author simon jiang
 * @time 2020/7/8 10:29
 */

@RestController
@RequestMapping("/user")
@Api(tags = {"用户信息"})
public class UserController {


    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;

    @Autowired
    private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private OauthClientDetailsService oauthClientDetailsService;

    @Autowired
    private SysRoleService sysRoleService;


    @PostMapping("/login")
    @ApiOperation("登录")
    public JsonResult login(@Valid @RequestBody UserLoginParamDto loginDto, BindingResult bindingResult) throws Exception {

        if (bindingResult.hasErrors()) {
            throw new Exception("登录信息错误，请确认后再试");
        }

        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getUsername, loginDto.getUsername()));

        if(user == null) {
            throw new Exception("没有该用户，请确认后再试");
        }

        String clientSecret = oAuth2ClientProperties.getClientId()+":"+oAuth2ClientProperties.getClientSecret();

        clientSecret = "Basic "+ Base64.getEncoder().encodeToString(clientSecret.getBytes());
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization",clientSecret);

        //授权请求信息
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.put("username", Collections.singletonList(loginDto.getUsername()));
        map.put("password", Collections.singletonList(loginDto.getPassword()));
        map.put("grant_type", Collections.singletonList(oAuth2ProtectedResourceDetails.getGrantType()));
        map.put("scope", oAuth2ProtectedResourceDetails.getScope());
        map.put("client_id", Collections.singletonList(oAuth2ProtectedResourceDetails.getClientId()));
        map.put("client_secret", Collections.singletonList(oAuth2ProtectedResourceDetails.getClientSecret()));
        //HttpEntity
        HttpEntity httpEntity = new HttpEntity(map,httpHeaders);
        //获取 Token
        return new JsonResult().success(restTemplate.exchange(oAuth2ProtectedResourceDetails.getAccessTokenUri(), HttpMethod.POST,httpEntity,OAuth2AccessToken.class).getBody());

    }

    @PostMapping("/register")
    @ApiOperation("个人用户注册")
    public JsonResult register(@RequestBody SysUser sysUser) {

        sysUserService.insert(sysUser, new ArrayList<String>(){{add(getDefaultRoleId());}});
        return new JsonResult();
    }

    @PostMapping("/updateUser")
    @ApiOperation("修改个人用户信息")
    public JsonResult updateUser(@RequestBody SysUser sysUser) {
        sysUserService.updateUser(sysUser);
        return new JsonResult();
    }


    @PostMapping("/clientRegister")
    @ApiOperation("服务注册")
    public JsonResult clientRegister(@RequestBody OauthClientDetails oauthClientDetails) {
        oauthClientDetailsService.clientRegister(oauthClientDetails);
        return new JsonResult();
    }


    /**
     * 获取默认角色的id
     * @return
     */
    private String getDefaultRoleId() {
        SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getIsDefault, true));
        if(sysRole == null) {
            throw new ServiceException("当前系统中不存在，默认角色");
        }
        return sysRole.getId();
    }
}
